<?php
@session_start();
require_once(dirname(__FILE__)."/../../../user/config.php");
require_once(dirname(__FILE__)."/../../../include/common.inc.php");
require_once DEDEINC.'/membermodel.cls.php';
global $dsql;
// $res = $dsql->GetOne("select * from wx_state order by id DESC limit 1");
// if($_GET['state']!=$res['state']){
//     ShowMsg('参数错误：5001', 'index.php',0,8);
// }
$weixin = $dsql->GetOne("select * from wx_info where id=1");
$AppID = $weixin['appid'];
$AppSecret = $weixin['appsecret'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json =  curl_exec($ch);
curl_close($ch);
$arr = json_decode($json, 1);
//得到 access_token 与 openid

$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json =  curl_exec($ch);
curl_close($ch);
$arr = json_decode($json, 1);

$char = "。、！？：；﹑•＂…‘’“”〝〞''∕¦‖—　〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔！¡？¿﹖﹌﹏﹋＇´ˊˋ―﹫︳︴¯＿￣﹢﹦﹤‐˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼（）";
        
$pattern = array(
    "/[[:punct:]]/i", //英文标点符号
    '/['.$char.']/u', //中文标点符号
    '/[ ]{2,}/'
);

$userid = trim(preg_replace($pattern, ' ', $arr['nickname']));
$pwd = md5(123456);
$uname = trim(preg_replace($pattern, ' ', $arr['nickname']));

$row = $dsql->GetOne("SELECT * FROM `#@__member` WHERE uname LIKE '$uname' ");
if(is_array($row))
{
    $userid = $userid.rand(1, 999);
    $uname = $userid;
}

//会员的默认金币
$dfscores = 0;
$dfmoney = 0;
$dfrank = $dsql->GetOne("SELECT money,scores FROM `#@__arcrank` WHERE rank='10' ");
if(is_array($dfrank))
{
    $dfmoney = $dfrank['money'];
    $dfscores = $dfrank['scores'];
}
$jointime = time();
$logintime = time();
$joinip = GetIP();
$loginip = GetIP();
$openid = $arr['openid'];
$unionid = $arr['unionid'];
$face = $arr['headimgurl'];

$mtype = '个人';
$member = $dsql->GetOne("SELECT * FROM `#@__member` WHERE unionid='$unionid'");

if($member) {
    
    $member_face = $dsql->GetOne("SELECT * FROM `#@__member` WHERE unionid='$unionid' and face='$face'");
    if(!$member_face){
        $dsql->ExecuteNoneQuery("UPDATE `#@__member` SET face = '$face' WHERE mid = ".$member['mid']);
    }
    $member_pwd = $dsql->GetOne("SELECT pwd FROM `#@__member` WHERE unionid='$unionid' ");
    
    if(!$member_pwd['pwd']){
        $dsql->ExecuteNoneQuery("UPDATE `#@__member` SET pwd = '$pwd' WHERE mid = ".$member['mid']);
    }

    $cfg_ml->PutLoginInfo($member['mid']);
    $cfg_ml->DelCache($cfg_ml->M_ID);

    echo exit('<script>top.location.href="/user?token=123'.$member['mid'].'"</script>');
}else{
    $inQuery = "INSERT INTO `#@__member` (`mtype` ,`userid` ,`pwd` ,`uname` ,`sex` ,`rank` ,`money` ,`email` ,`scores` ,
            `matt`, `spacesta` ,`face`,`safequestion`,`safeanswer` ,`jointime` ,`joinip` ,`logintime` ,`loginip` ,`openid`,`unionid`)
           VALUES ('$mtype','$userid','$pwd','$uname','$sex','10','$dfmoney','','$dfscores',
           '0','','$face','0','','$jointime','$joinip','$logintime','$loginip','$openid','$unionid'); ";
    if($dsql->ExecuteNoneQuery($inQuery)) {
        $mid = $dsql->GetLastID();

        //写入默认会员详细资料
        if ($mtype == '个人') {
            $space = 'person';
        } else if ($mtype == '企业') {
            $space = 'company';
        } else {
            $space = 'person';
        }

        //写入默认统计数据
        $membertjquery = "INSERT INTO `#@__member_tj` (`mid`,`article`,`album`,`archives`,`homecount`,`pagecount`,`feedback`,`friend`,`stow`)
                       VALUES ('$mid','0','0','0','0','0','0','0','0'); ";
        $dsql->ExecuteNoneQuery($membertjquery);

        //写入默认空间配置数据
        $spacequery = "INSERT INTO `#@__member_space`(`mid` ,`pagesize` ,`matt` ,`spacename` ,`spacelogo` ,`spacestyle`, `sign` ,`spacenews`)
                        VALUES('{$mid}','10','0','{$uname}的空间','','$space','',''); ";
        $dsql->ExecuteNoneQuery($spacequery);

        //写入其它默认数据
        $dsql->ExecuteNoneQuery("INSERT INTO `#@__member_flink`(mid,title,url) VALUES('$mid','织梦内容管理系统','http://www.dedecms.com'); ");

        $membermodel = new membermodel($mtype);

        $modid = $membermodel->modid;
        $modid = empty($modid) ? 0 : intval(preg_replace("/[^\d]/", '', $modid));
        $modelform = $dsql->getOne("SELECT * FROM #@__member_model WHERE id='$modid' ");

        if (!is_array($modelform)) {
            showmsg('模型表单不存在', '-1');
            exit();
        } else {
            $dsql->ExecuteNoneQuery("INSERT INTO `{$membermodel->table}` (`mid`) VALUES ('{$mid}');");
        }

        //----------------------------------------------
        //模拟登录
        //---------------------------
        $cfg_ml = new MemberLogin(-1);
        $rs = $cfg_ml->PutLoginInfo($mid);
        
        if ($rs) {
            echo exit('<script>top.location.href="/user?token=123'.$mid.'"</script>');
        } else {
            require_once(DEDEMEMBER . "/templets/reg-new4.htm");
            exit;
        }
    } else {
        ShowMsg('注册失败！请联系管理人员。');
        exit();
    }
}